package com.example.customer01.controller;

import com.example.customer01.pojo.Admin;
import com.example.customer01.service.AdminService;
import com.example.customer01.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/admin")
public class AdminController {
    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Resource
    private AdminService adminService;

    @Autowired
    private FileService fileService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");
        
        logger.info("尝试登录: username={}", username);
        
        Admin admin = adminService.login(username, password);
        if (admin != null) {
            // 生成 token
            String token = UUID.randomUUID().toString();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", new HashMap<String, Object>() {{
                put("token", token);
                put("admin", admin);
            }});
            
            logger.info("登录成功: adminId={}, role={}", admin.getAdminId(), admin.getRole());
            return ResponseEntity.ok(response);
        } else {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "用户名或密码错误");
            
            logger.warn("登录失败: username={}", username);
            return ResponseEntity.ok(response);
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody Admin admin) {
        if (adminService.checkUsernameExists(admin.getUsername())) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "用戶名已存在");
            return ResponseEntity.ok(response);
        }

        boolean success = adminService.register(admin);
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", success ? "註冊成功" : "註冊失敗");
        return ResponseEntity.ok(response);
    }

    @GetMapping("/check-username")
    public ResponseEntity<?> checkUsername(@RequestParam String username) {
        boolean exists = adminService.checkUsernameExists(username);
        Map<String, Object> response = new HashMap<>();
        response.put("exists", exists);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/info")
    public ResponseEntity<?> getAdminInfo(@RequestParam Integer adminId) {
        Admin admin = adminService.getById(adminId);
        if (admin != null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", admin);
            return ResponseEntity.ok(response);
        } else {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "管理員不存在");
            return ResponseEntity.ok(response);
        }
    }

    @PutMapping("/update")
    public ResponseEntity<?> updateAdmin(@RequestBody Admin admin) {
        boolean success = adminService.updateById(admin);
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", success ? "更新成功" : "更新失敗");
        return ResponseEntity.ok(response);
    }

    @PutMapping("/password")
    public ResponseEntity<?> updatePassword(@RequestBody Map<String, String> passwordRequest) {
        // 驗證必要參數
        if (passwordRequest == null || 
            !passwordRequest.containsKey("adminId") || 
            !passwordRequest.containsKey("oldPassword") || 
            !passwordRequest.containsKey("newPassword")) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "缺少必要參數");
            return ResponseEntity.ok(response);
        }

        try {
            String oldPassword = passwordRequest.get("oldPassword");
            String newPassword = passwordRequest.get("newPassword");
            Integer adminId = Integer.parseInt(passwordRequest.get("adminId"));

            boolean success = adminService.updatePassword(adminId, oldPassword, newPassword);
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "密碼修改成功" : "密碼修改失敗");
            return ResponseEntity.ok(response);
        } catch (NumberFormatException e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "無效的管理員ID");
            return ResponseEntity.ok(response);
        }
    }

    @PostMapping("/{adminId}/photo")
    public ResponseEntity<String> uploadPhoto(
            @PathVariable Integer adminId,
            @RequestParam("file") MultipartFile file) {
        // 上傳照片
        String photoUrl = fileService.uploadFile(file, "admin/photos");
        
        // 更新管理員信息
        Admin admin = adminService.getById(adminId);
        if (admin != null) {
            // 刪除舊照片
            if (admin.getPhotoUrl() != null) {
                fileService.deleteFile(admin.getPhotoUrl());
            }
            
            // 更新照片URL
            admin.setPhotoUrl(photoUrl);
            adminService.updateById(admin);
            
            return ResponseEntity.ok(photoUrl);
        }
        
        return ResponseEntity.notFound().build();
    }

    @GetMapping("/{adminId}/photo")
    public ResponseEntity<Admin> getAdminWithPhoto(@PathVariable Integer adminId) {
        Admin admin = adminService.getById(adminId);
        if (admin != null) {
            return ResponseEntity.ok(admin);
        }
        return ResponseEntity.notFound().build();
    }
} 